# user_service.py
import logging
import os
import requests


from flask import Flask, jsonify, Response, request

from prometheus_client import generate_latest, Counter, Gauge, Histogram


REQUEST_COUNT = Counter('request_count', 'App Request Count')
REQUEST_LATENCY = Histogram('request_latency', 'Request latency')
IN_PROGRESS = Gauge('in_progress', 'Number of requests in progress')


log_dir = os.path.dirname(os.path.abspath(__file__))

log_path = os.path.join(log_dir,'logs')
if not os.path.exists(log_path):
    os.makedirs(log_path)
                            
log_file_path = os.path.join(log_path,'user_service.log')
logging.basicConfig(filename=log_file_path, level=logging.INFO)
# logging.basicConfig(filename='/var/log/user_service.log', level=logging.INFO)
logger = logging.getLogger(__name__)


from jaeger_client import Config

def init_tracer(service):
    config = Config(
        config={
            'sampler': {'type': 'const', 'param': 1},
            'local_agent': {
                'reporting_host': 'jaeger',
                'reporting_port': '6831',
            },
            'logging': True,
        },
        service_name=service,
        validate=True,
    )
    return config.initialize_tracer()



app = Flask(__name__)
tracer = init_tracer('user-service')


@app.before_request
def start_trace():
    with tracer.start_span('request') as span:
        span.log_kv({'event': f'request:{request}', 'life': 42})


@app.after_request
def end_trace(response):
    with tracer.start_span('response') as span:
        span.log_kv({'event': f'response:{response}', 'life': 42})
        return response


@app.route('/users')
def get_users():
    REQUEST_COUNT.inc()
    with REQUEST_LATENCY.time():
        users = [
            {'id': 1, 'name': 'Alice'},
            {'id': 2, 'name': 'Bob'}
        ]
        logger.info('Fetched users: %s', users)
        return jsonify(users)
    IN_PROGRESS.dec()

def register_service():
    payload = {
        "ID": "user-service",
        "Name": "user-service",
        "Address": "user-service",
        "Port": 5001
    }
    requests.put('http://consul:8500/v1/agent/service/register', json=payload)

@app.route('/metrics')
def metrics():
    return Response(generate_latest(), mimetype='text/plain')


if __name__ == '__main__':
    register_service()
    app.run(host='0.0.0.0', port=5001)
